<?php
require APPPATH . "libraries/ApiController.php";
class product extends ApiController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function list()
    {
        $token = $this->verifyToken();
        if ($token) {
            $data = $this->getKeys([
				["cateid", true, "类目id"]
			], "post");
				$this->db->select("proid,product.cateid,title as catetitle,kucun,protitle,product.desc,price,cost,product.shopid,thumb");
				$this->db->where("product.cateid", $data["cateid"]);
				$this->db->where("product.shopid", $token["shopid"]);
				$this->db->join("product_category","product_category.cateid=product.cateid",'left');
				$list = $this->db->get("product")->result_array();
				for ($i = 0; $i < count($list); $i++) {
					$list[$i]["count"]=0;
					if($list[$i]["thumb"]!=""){
						$list[$i]["thumb"] =$this->config->item("domain").$list[$i]["thumb"];
					}
				}
				$this->WRITE("code", 1);
				$this->WRITE("list", $list);
				$this->RESPONSE();
        }
    }
	
	public function query(){
		$token = $this->verifyToken();
		if ($token) {
		    $data = $this->getKeys([
				["protitle",false,"商品名称",""]
			], "post");
			
			$this->db->like("protitle",$data["protitle"]);
			$this->db->select("proid,product.cateid,title as catetitle,kucun,protitle,product.desc,price,cost,product.shopid,thumb");
			$this->db->where("product.shopid", $token["shopid"]);
			$this->db->join("product_category","product_category.cateid=product.cateid",'left');
			$list=$this->db->get("product")->result_array();
				
			for ($i = 0; $i < count($list); $i++) {
				if($list[$i]["thumb"]!=""){
					$list[$i]["thumb"] =$this->config->item("domain").$list[$i]["thumb"];
				}
			}
			
			
			$this->WRITE("code", 1);
			$this->WRITE("msg","查询成功");
			$this->WRITE("list", $list);
			$this->RESPONSE();
			
		}
		
	}
	

    public function create()
    {
        $token = $this->verifyToken();
        if ($token) {
            $data = $this->getKeys(
                [
                    ["cateid", true, "类目id"],
                    ["protitle", true, "分类名称"],
					["kucun",true,"初始始库存"],
                    ["price", true, "商品售价"],
					["desc", false, "商品描述", ""],
                    ["cost", false, "商品成本", 0],
                ],"post" );

            //检测目录是否存在,不存在则直接创建
           //上传头像
		   $folder=$this->config->item("upload")."/uploads/product/";
		   var_dump(file_exists($folder));
           if (!file_exists($this->config->item("upload")."/uploads/product/")) {
               mkdir($this->config->item("upload")."/uploads/product/", 0777, true);
           }

          foreach ($_FILES as $key => $file) {
           	if (strpos($file["type"], 'image') !== false) {
           		$ext = substr(strrchr($file["type"], "/"), 1);
           		$filename = 'pro_'.uniqid().'.'.$ext;
           		$path='/uploads/product/'.$filename;
           		$productUrl=$this->config->item("domain").'/uploads/product/'.$filename;
           		if (move_uploaded_file($file["tmp_name"],$this->config->item("upload").$path)) {
           			//上传成功
           			$data["thumb"]=$path;
           		}
           	}
           }
		   $data["shopid"]=$token["shopid"];
           $this->db->insert("product", $data);
           $data["proid"] = $this->db->insert_id();
           $result = $data;
           $result["thumb"] = [
                "name" => $data["thumb"],
                "status" => "success",
				"type"=>"image",
                "url" =>$this->config->item("domain").$data["thumb"],
            ];

            $this->WRITE("code", 1);
			$this->WRITE("msg","商品添加成功");
            $this->WRITE("data", $result);
            $this->RESPONSE();
        }
    }

    public function update() {
		$token = $this->verifyToken();
		if ($token) {
		    $data = $this->getKeys(
		        [
					["proid", true, "产品id"],
		            ["cateid", true, "类目id"],
		            ["protitle", true, "分类名称"],
					["kucun",true,"初始始库存"],
					["thumb",false,"缩略图",""],
		            ["price", true, "商品售价"],
					["desc", false, "商品描述", ""],
		            ["cost", false, "商品成本", 0],
		        ],"post" );
			
			$this->db->where("proid",$data["proid"]);
			$othumb=$this->db->select("thumb")->get("product")->row_array()["thumb"];
			
			//判断是否删除原图片
			if($data["thumb"]==""){
				if($othumb!=""){
					//var_dump("删除原图片");
					//删除原图片
					if(file_exists($this->config->item("upload").$othumb)){
						unlink($this->config->item("upload").$othumb);
					}
				}
				//var_dump("删除了原图片,开始上传新图");
				foreach ($_FILES as $key => $file) {
					if (strpos($file["type"], 'image') !== false  ) {
						
						$ext = substr(strrchr($file["type"], "/"), 1);
						$filename = 'pro_'.uniqid().'.'.$ext;
						$path='/uploads/product/'.$filename;
						if (move_uploaded_file($file["tmp_name"],$this->config->item("upload").$path)) {
							//上传成功
							$data["thumb"]=$path;
						}
					}
				}
				
				
			}else{
				//var_dump("没替换，保持不变");
				$data["thumb"]=str_replace($this->config->item("domain"),"",$data["thumb"]);
				
			}
			$data["shopid"]=$token["shopid"];
			$this->db->where("proid",$data["proid"]);
			$this->db->update("product", $data);
			
			$this->WRITE("code", 1);
			$this->WRITE("msg","保存成功");
			$this->RESPONSE();
		}
	}
	
	public function remove(){
		$token = $this->verifyToken();
		if ($token) {
		    $data = $this->getKeys([["proid", true, "产品id"]],'post');
			
			$this->db->where("proid",$data["proid"]);
			$this->db->where("shopid",$token["shopid"]);
			$row=$this->db->get("product")->row_array();
			
			//删除商品图片
			if($row){
				if(file_exists($this->config->item("upload").$row["thumb"])){
					unlink($this->config->item("upload").$row["thumb"]);
				}
				$this->db->where("proid",$data["proid"]);
				$this->db->where("shopid",$token["shopid"]);
				$res=$this->db->delete("product");
				
				$this->WRITE("code", 1);
				$this->WRITE("msg","删除成功");
				$this->RESPONSE();
			}else{
				$this->WRITE("code", 0);
				$this->WRITE("msg","删除失败");
				$this->RESPONSE();
			}
		}
	}
}
